-- Most of this code taken from https://github.com/CosminPOP/TWAssignments and https://github.com/Ko0z/XLoot
-- Main idea - keep it simple, no fancy functions
local MLBC = CreateFrame("Frame", "MasterLootByClassFrame")
local RaidDropDown = CreateFrame("Frame", "MLBC_RaidDropDown", UIParent, "UIDropDownMenuTemplate")

MasterLootLogDB = MasterLootLogDB or {
    keepDays = 7,         -- 记录保留天数
    isMonitorChat = true, -- 是否监控团队频道  true: 所有人都可以保存分配信息。  false: 只有分配者保存装备分配记录（两张情况都需要分配者安装此插件才生效）
    qualityThreshold = 2, -- 过滤记录品质最低阈值 看下方 Quality 表
    log = {},             -- 详细记录信息
    debug = false,         -- 调试模式
    minimapAngle = 180    -- 图标显示在小地图上的角度
}

local Quality = {
    [0] = "灰色",
    [1] = "白色",
    [2] = "绿色",
    [3] = "蓝色",
    [4] = "紫色",
    [5] = "橙色",
    [6] = "神器",
}

local QUALITY_COLOR = {
    ["9d9d9d"] = 0, -- 粗糙
    ["ffffff"] = 1, -- 普通
    ["1eff00"] = 2, -- 优秀
    ["0070dd"] = 3, -- 精良
    ["a335ee"] = 4, -- 史诗
    ["ff8000"] = 5, -- 传说
    ["e6cc80"] = 6, -- 神器
}

local MasterLootLogFrame -- GUI 引用，延迟创建

-- 新增一张映射表
local nameToSubgroup = {} -- name → subgroup

MLBC:RegisterEvent("PLAYER_LOGIN")
MLBC:RegisterEvent("OPEN_MASTER_LOOT_LIST")
MLBC:RegisterEvent("RAID_ROSTER_UPDATE")
MLBC:RegisterEvent("LOOT_SLOT_CLEARED")

MLBC.colors = {}
MLBC.colors["WARRIOR"] = "|cffc79c6e"
MLBC.colors["DRUID"] = "|cffff7d0a"
MLBC.colors["PALADIN"] = "|cfff58cba"
MLBC.colors["WARLOCK"] = "|cff9482c9"
MLBC.colors["MAGE"] = "|cff69ccf0"
MLBC.colors["PRIEST"] = "|cffffffff"
MLBC.colors["ROGUE"] = "|cfffff569"
MLBC.colors["HUNTER"] = "|cffabd473"
MLBC.colors["SHAMAN"] = "|cff0070de"

MLBC.raid = {}
MLBC.raid["WARRIOR"] = {}
MLBC.raid["DRUID"] = {}
MLBC.raid["PALADIN"] = {}
MLBC.raid["WARLOCK"] = {}
MLBC.raid["MAGE"] = {}
MLBC.raid["PRIEST"] = {}
MLBC.raid["ROGUE"] = {}
MLBC.raid["HUNTER"] = {}
MLBC.raid["SHAMAN"] = {}

local function debugPrint(text)
    if MasterLootLogDB.debug then
        DEFAULT_CHAT_FRAME:AddMessage(text)
    end
end

local function wipe(tbl)
    for k in pairs(tbl) do tbl[k] = nil end
    table.setn(tbl, 0)
end

local function FillRaidData()
    for _, data in pairs(MLBC.raid) do wipe(data) end
    -- 1. 清空表
    wipe(nameToSubgroup)

    -- 2. 重新填充
    if UnitInRaid("player") then
        for i = 1, GetNumRaidMembers() do
            local name, _, subgroup = GetRaidRosterInfo(i)
            if name then
                local _, class = UnitClass("raid" .. i)
                table.insert(MLBC.raid[class], name)
                nameToSubgroup[name] = subgroup or 0
            end
        end
    elseif UnitInParty("player") then
        -- 5 人本全部算小队 1
        local _, playerClass = UnitClass("player")
        local playerName = UnitName("player")
        table.insert(MLBC.raid[playerClass], playerName)
        nameToSubgroup[playerName] = 1

        for i = 1, GetNumPartyMembers() do
            local name = UnitName("party" .. i)
            if name then
                local _, unitClass = UnitClass("party" .. i)
                table.insert(MLBC.raid[unitClass], name)
                nameToSubgroup[name] = 1
            end
        end
    end

    -- 3. 关键：按小队号再按名字排序
    for class in pairs(MLBC.raid) do
        table.sort(MLBC.raid[class], function(a, b)
            local sgA = nameToSubgroup[a] or 99
            local sgB = nameToSubgroup[b] or 99
            if sgA == sgB then
                return a < b     -- 同小队再按名字字母
            else
                return sgA < sgB -- 不同小队按小队号
            end
        end)
    end
end

local function GetCandidateID(name)
    if GetNumRaidMembers() > 0 then
        for i = 1, 40 do
            if name == GetMasterLootCandidate(i) then return i end
        end
    end
    DEFAULT_CHAT_FRAME:AddMessage(
        "|cffcc6666[MasterLootByClass]|r|cffffff00 " .. name .. " 无法接收这个物品.|r")
end

local function IsOffline(name)
    for i = 1, GetNumRaidMembers() do
        if GetRaidRosterInfo(i) then
            local n, _, _, _, _, _, o = GetRaidRosterInfo(i)
            if n == name and o == "Offline" then return true end
        end
    end
    return false
end

-- 根据名字反查职业
local function ClassOfName(name)
    for class, roster in pairs(MLBC.raid) do
        for _, n in ipairs(roster) do if n == name then return class end end
    end
end

local function GuessQualityFromLink(link)
    local rgb = string.lower(string.sub(link, 5, 10))
    local quality = QUALITY_COLOR[rgb]
    return quality
end

-- 品质判断函数
local function ItemQualityOK(link)
    if not link then return false end
    local itemID = string.match(link, "|Hitem:(%d+)")
    local _, _, quality = GetItemInfo(itemID)

    -- 如果 GetItemInfo 返回空，再用备用方案
    if not quality then
        debugPrint("|CFF00FF00本次是通过颜色猜的品质")
        quality = GuessQualityFromLink(link)
    end
    debugPrint(link .. " 的品质是: " .. tostring(quality))
    return quality >= (MasterLootLogDB.qualityThreshold or 3)
end

local function GiveToRandom()
    local max = GetNumRaidMembers() and 40 or 5
    local name, id
    local item = LootFrame.selectedSlot
    local link = GetLootSlotLink(item)

    while not name do
        id = math.random(1, max)
        name = GetMasterLootCandidate(id)
    end
    if name and id and item and link then
        if not ItemQualityOK(link) then
            debugPrint("不符合记录，直接分配")
            GiveMasterLoot(item, id)
            return
        end
        -- =====================
        local class = ClassOfName(name) -- 用上面函数拿职业
        local color = MLBC.colors[class] or "|cffffffff"
        SendChatMessage("正在R点...", "RAID") -- ("Rolling the dice...", "RAID")
        SendChatMessage(string.format("%s 随机分配给  (小队%s) %s%s|r", link, nameToSubgroup[name], color, name), "RAID")

        -- 记入 CD 日志
        table.insert(MasterLootLogDB.log, {
            itemLink = link,
            player = color .. name .. "|r(随机)",
            time = time(),
            dateStr = date("%m-%d %H:%M")
        })

        GiveMasterLoot(item, id)
    end
end

local function GiveLoot(name)
    local item = LootFrame.selectedSlot
    local id = GetCandidateID(name)
    if not item or not id then return end

    local link = GetLootSlotLink(item)
    if not link then return end
    -- ===== 新增过滤 =====
    if not ItemQualityOK(link) then
        debugPrint("不符合记录，直接分配")
        GiveMasterLoot(item, id) -- 直接分，不通报/记录
        return
    end
    -- =====================

    local class = ClassOfName(name) -- 用上面函数拿职业
    local color = MLBC.colors[class] or "|cffffffff"
    SendChatMessage(string.format("%s 分配给  (小队%s) %s%s|r", link, nameToSubgroup[name], color, name), "RAID")

    -- 记入 CD 日志
    table.insert(MasterLootLogDB.log, {
        itemLink = link,
        player = color .. name .. "|r",
        time = time(),
        dateStr = date("%m-%d %H:%M")
    })


    GiveMasterLoot(item, id)
end

local info = {}

local function BuildRaidMenu()
    -- 1) 先判断权限
    local lootMethod, masterID = GetLootMethod()
    local amIMaster = lootMethod == "master" and (masterID or -1) == 0

    -- 2) 没有权限：只画一个红色提示按钮
    if not amIMaster then
        wipe(info)
        info.text = "|cffff0000你没有分配权限|r"
        info.isTitle = true -- 灰色化、不可点
        info.notCheckable = true
        info.disabled = true
        UIDropDownMenu_AddButton(info)
        return -- 直接结束
    end

    if UnitInRaid("player") and UIDROPDOWNMENU_MENU_LEVEL == 1 then
        wipe(info)
        info.text = GIVE_LOOT
        info.isTitle = true
        info.textHeight = 12
        info.notCheckable = true
        UIDropDownMenu_AddButton(info)

        wipe(info)
        info.text = "自己"
        info.textHeight = 12
        info.disabled = false
        info.isTitle = false
        info.notCheckable = true
        info.func = GiveLoot
        info.arg1 = UnitName("player")
        UIDropDownMenu_AddButton(info)

        wipe(info)
        info.text = "随机分配"
        info.disabled = false
        info.textHeight = 12
        info.isTitle = false
        info.notCheckable = true
        info.func = GiveToRandom
        UIDropDownMenu_AddButton(info)

        wipe(info)
        info.text = ""
        info.disabled = true
        UIDropDownMenu_AddButton(info)

        local classOrder = {"WARRIOR", "DRUID", "PALADIN", "WARLOCK", "MAGE", "PRIEST", "ROGUE", "HUNTER", "SHAMAN"}
        local classLocales = {
            WARRIOR = "战士",
            DRUID = "德鲁伊",
            PALADIN = "圣骑士",
            WARLOCK = "术士",
            MAGE = "法师",
            PRIEST = "牧师",
            ROGUE = "盗贼",
            HUNTER = "猎人",
            SHAMAN = "萨满"
        }
    
        for _, class in ipairs(classOrder) do
            if next(MLBC.raid[class]) then
                wipe(info)
                info.text = MLBC.colors[class] .. classLocales[class]
                info.textHeight = 12
                info.notCheckable = true
                info.hasArrow = true
                info.value = class
                UIDropDownMenu_AddButton(info)
            end
        end
--[[
        -- wipe(info)
        -- info.text = MLBC.colors["WARRIOR"] .. "战士"
        -- info.textHeight = 12
        -- info.notCheckable = true
        -- info.hasArrow = true
        -- info.value = "WARRIOR"
        -- if next(MLBC.raid["WARRIOR"]) then UIDropDownMenu_AddButton(info) end

        -- wipe(info)
        -- info.text = MLBC.colors["DRUID"] .. "德鲁伊"
        -- info.textHeight = 12
        -- info.notCheckable = true
        -- info.hasArrow = true
        -- info.value = "DRUID"
        -- if next(MLBC.raid["DRUID"]) then UIDropDownMenu_AddButton(info) end

        -- wipe(info)
        -- info.text = MLBC.colors["PALADIN"] .. "圣骑士"
        -- info.textHeight = 12
        -- info.notCheckable = true
        -- info.hasArrow = true
        -- info.value = "PALADIN"
        -- if next(MLBC.raid["PALADIN"]) then UIDropDownMenu_AddButton(info) end

        -- wipe(info)
        -- info.text = MLBC.colors["WARLOCK"] .. "术士"
        -- info.textHeight = 12
        -- info.notCheckable = true
        -- info.hasArrow = true
        -- info.value = "WARLOCK"
        -- if next(MLBC.raid["WARLOCK"]) then UIDropDownMenu_AddButton(info) end

        -- wipe(info)
        -- info.text = MLBC.colors["MAGE"] .. "法师"
        -- info.textHeight = 12
        -- info.notCheckable = true
        -- info.hasArrow = true
        -- info.value = "MAGE"
        -- if next(MLBC.raid["MAGE"]) then UIDropDownMenu_AddButton(info) end

        -- wipe(info)
        -- info.text = MLBC.colors["PRIEST"] .. "牧师"
        -- info.textHeight = 12
        -- info.notCheckable = true
        -- info.hasArrow = true
        -- info.value = "PRIEST"
        -- if next(MLBC.raid["PRIEST"]) then UIDropDownMenu_AddButton(info) end

        -- wipe(info)
        -- info.text = MLBC.colors["ROGUE"] .. "盗贼"
        -- info.textHeight = 12
        -- info.notCheckable = true
        -- info.hasArrow = true
        -- info.value = "ROGUE"
        -- if next(MLBC.raid["ROGUE"]) then UIDropDownMenu_AddButton(info) end

        -- wipe(info)
        -- info.text = MLBC.colors["HUNTER"] .. "猎人"
        -- info.textHeight = 12
        -- info.notCheckable = true
        -- info.hasArrow = true
        -- info.value = "HUNTER"
        -- if next(MLBC.raid["HUNTER"]) then UIDropDownMenu_AddButton(info) end

        -- wipe(info)
        -- info.text = MLBC.colors["SHAMAN"] .. "萨满"
        -- info.textHeight = 12
        -- info.notCheckable = true
        -- info.hasArrow = true
        -- info.value = "SHAMAN"
        -- if next(MLBC.raid["SHAMAN"]) then UIDropDownMenu_AddButton(info) end

]]
    elseif UnitInParty("player") and not UnitInRaid("player") and
        UIDROPDOWNMENU_MENU_LEVEL == 1 then
        local candidate, class
        for i = 1, MAX_PARTY_MEMBERS + 1 do
            candidate = GetMasterLootCandidate(i)
            if candidate then
                for k in pairs(MLBC.raid) do
                    for _, name in pairs(MLBC.raid[k]) do
                        if name == candidate then
                            class = k
                            break
                        end
                    end
                end
                if class then
                    local color = MLBC.colors[class]
                    wipe(info)
                    info.text = color .. candidate
                    info.textHeight = 12
                    info.notCheckable = 1
                    info.arg1 = LootFrame.selectedSlot
                    info.arg2 = i
                    info.func = GiveMasterLoot
                    UIDropDownMenu_AddButton(info)
                end
            end
        end
    end

    if UIDROPDOWNMENU_MENU_LEVEL == 2 then
        for _, player in next, MLBC.raid[UIDROPDOWNMENU_MENU_VALUE] do
            wipe(info)
            local class = UIDROPDOWNMENU_MENU_VALUE
            local color = MLBC.colors[class]
            info.notCheckable = true
            info.hasArrow = false
            info.func = GiveLoot
            info.arg1 = player
            info.textHeight = 12
            -- 拿到小队号，拼在前面
            local sg = nameToSubgroup[player] or 0
            local sgText = sg > 0 and "[" .. sg .. "]" or ""

            if IsOffline(player) then
                info.disabled = true
                info.text = sgText .. player
            else
                info.disabled = false
                info.text = sgText .. color .. player .. "|r"
            end
            UIDropDownMenu_AddButton(info, UIDROPDOWNMENU_MENU_LEVEL)
        end
    end
end

local lastSelectedSlot

LootFrame:UnregisterEvent("OPEN_MASTER_LOOT_LIST")
LootFrame:SetScript("OnMouseUp", function()
    CloseDropDownMenus()
    lastSelectedSlot = nil
end)

DropDownList1:SetScript("OnHide", function()
    CloseDropDownMenus(2)
    OPEN_DROPDOWNMENUS[1] = nil
    lastSelectedSlot = nil
end)

MLBC:SetScript("OnEvent", function()
    if event == "PLAYER_LOGIN" then
        local sv = MasterLootLogDB
        -- 清除过期记录
        local today = time()
        local keepSeconds = sv.keepDays * 60 * 60 * 24
        for i = table.getn(sv.log), 1, -1 do
            local record = sv.log[i]
            if record.time then
                if (today - record.time) > keepSeconds then
                    table.remove(sv.log, i)
                end
            end
        end

        -- 品质阈值
        sv.qualityThreshold = sv.qualityThreshold or 3 -- 默认蓝色
        MasterLootLogDB = sv
    end

    local lootmethod, masterlooterPartyID = GetLootMethod()
    if lootmethod == "master" then
        if event == "RAID_ROSTER_UPDATE" then
            FillRaidData()
        elseif event == "OPEN_MASTER_LOOT_LIST" then
            FillRaidData()
            UIDropDownMenu_Initialize(RaidDropDown, BuildRaidMenu, "MENU")
            if LootFrame.selectedLootButton ~= lastSelectedSlot then
                DropDownList1:Hide()
                ToggleDropDownMenu(1, nil, RaidDropDown,
                    LootFrame.selectedLootButton, 0, 0)
                lastSelectedSlot = LootFrame.selectedLootButton
            else
                DropDownList1:Hide()
                lastSelectedSlot = nil
            end
        elseif event == "LOOT_SLOT_CLEARED" then
            CloseDropDownMenus()
            lastSelectedSlot = nil
        end
    end
end)

UnitPopupButtons["ITEM_QUALITY1_DESC"] = {
    text = TEXT(ITEM_QUALITY1_DESC),
    dist = 0,
    color = ITEM_QUALITY_COLORS[1]
}
table.insert(UnitPopupMenus["LOOT_THRESHOLD"], 1, "ITEM_QUALITY1_DESC")

local Original_UnitPopup_OnClick = UnitPopup_OnClick

local function Hook_UnitPopup_OnClick()
    Original_UnitPopup_OnClick()
    local button = arg1
    if button == "ITEM_QUALITY1_DESC" or button == "ITEM_QUALITY2_DESC" or
        button == "ITEM_QUALITY3_DESC" or button == "ITEM_QUALITY4_DESC" then
        SetLootThreshold(this:GetID())
        local color = ITEM_QUALITY_COLORS[this:GetID()]
        UIDropDownMenu_SetButtonText(1, 3, UnitPopupButtons[button].text,
            color.r, color.g, color.b)
    end
end

UnitPopup_OnClick = Hook_UnitPopup_OnClick

------------------------------------------------
-- 创建 GUI
------------------------------------------------
local function CreateLogGUI()
    -- 主窗体
    local f = CreateFrame("Frame", "MasterLootLogFrame", UIParent)
    f:SetWidth(430)
    f:SetHeight(300)
    f:SetPoint("CENTER", 0, 0)
    f:SetMovable(true)
    f:EnableMouse(true)
    f:RegisterForDrag("LeftButton")
    f:SetScript("OnMouseDown", function()
        this:StartMoving()
    end)
    f:SetScript("OnMouseUp", function()
        this:StopMovingOrSizing()
    end)

    -- 边框
    f.bg = f:CreateTexture(nil, "BACKGROUND")
    f.bg:SetTexture("Interface\\DialogFrame\\UI-DialogBox-Background")
    f.bg:SetAllPoints(f)

    f.border = CreateFrame("Frame", nil, f)
    f.border:SetPoint("TOPLEFT", -10, 10)
    f.border:SetPoint("BOTTOMRIGHT", 10, -10)
    for _, edge in ipairs({ "TOP", "BOTTOM", "LEFT", "RIGHT", "TOPLEFT", "TOPRIGHT", "BOTTOMLEFT", "BOTTOMRIGHT" }) do
        local t = f.border:CreateTexture(nil, "BORDER")
        t:SetTexture("Interface\\DialogFrame\\UI-DialogBox-" .. edge)
        t:SetWidth(64)
        t:SetHeight(64)
        t:SetPoint(edge, 0, 0)
    end

    -- 标题条
    f.title = f:CreateFontString(nil, "OVERLAY", "GameFontNormal")
    f.title:SetPoint("TOP", 0, -15)
    f.title:SetFont(STANDARD_TEXT_FONT, 13, "OUTLINE")
    f.title:SetTextColor(0, 255, 255)
    f.title:SetText(string.format("MasterLoot 本周分配记录（只记录 %s%s|r 及以上品质）",
        ITEM_QUALITY_COLORS[MasterLootLogDB.qualityThreshold].hex, Quality[MasterLootLogDB.qualityThreshold]))

    -- 关闭按钮
    f.close = CreateFrame("Button", nil, f, "UIPanelCloseButton")
    f.close:SetPoint("TOPRIGHT", -5, -5)

    -- 滚动框架
    local scroll = CreateFrame("ScrollFrame", "MasterLootCDScroll", f, "UIPanelScrollFrameTemplate")
    scroll:SetWidth(385)
    scroll:SetHeight(240)
    scroll:SetPoint("TOP", 0, -35)
    f.scroll = scroll

    -- 内容子帧
    local content = CreateFrame("Frame", nil, scroll)
    content:SetWidth(385)
    content:SetHeight(1) -- 动态
    scroll:SetScrollChild(content)
    f.content = content


    -- 刷新函数
    f.Refresh = function(self)
        -- 1. 清空旧行
        for _, c in ipairs({ self.content:GetChildren() }) do c:Hide() end
        if MasterLootLogDB.log then
            local h = 0
            for _, v in ipairs(MasterLootLogDB.log) do
                local line = self.content:CreateFontString(nil, "OVERLAY", "GameFontNormal")
                line:SetWidth(340)
                line:SetJustifyH("LEFT")
                line:SetPoint("TOPLEFT", 10, -h)
                line:SetText(string.format("%s  %s → %s", v.dateStr, v.itemLink, v.player))
                h = h + line:GetHeight() + 2
            end

            -- 2. 设置子帧高度
            self.content:SetHeight(h + 2)

            -- 3. 关键：让 ScrollFrame 重新计算可滚动区域
            self.scroll:UpdateScrollChildRect()
        end
    end

    f:Hide()
    return f
end

local function ToggleFrame()
    if not MasterLootLogFrame then
        MasterLootLogFrame = CreateLogGUI()
    end
    if MasterLootLogFrame:IsVisible() then
        MasterLootLogFrame:Hide()
    else
        MasterLootLogFrame:Show()
        MasterLootLogFrame:Refresh()
    end
end

local function ToggleMonitorChat()
    if (MasterLootLogDB.isMonitorChat) then
        MasterLootLogDB.isMonitorChat = false
        DEFAULT_CHAT_FRAME:AddMessage("当前状态：只有自己是分配者才能记录")
    else
        MasterLootLogDB.isMonitorChat = true
        DEFAULT_CHAT_FRAME:AddMessage("当前状态：监控聊天频道,自己不是分配者也能记录（分配者也需要装此插件）")
    end
end

------------------------------------------------
-- 命令
------------------------------------------------
SLASH_MLBC1 = "/mlbc"
SLASH_MLBC2 = "/MasterLootByClass"
SlashCmdList["MLBC"] = function(param)
    local p = strlower(strtrim(param or ""))

    -- 帮助信息
    local function printHelp()
        DEFAULT_CHAT_FRAME:AddMessage("|cff33ff99[MasterLootByClass]|r 命令帮助：")
        DEFAULT_CHAT_FRAME:AddMessage("  /mlbc 或 /mlbc h        显示此帮助")
        DEFAULT_CHAT_FRAME:AddMessage("  /mlbc show 或 s         打开分配记录窗口")
        DEFAULT_CHAT_FRAME:AddMessage("  /mlbc toggle 或 t       切换聊天监控模式")
        DEFAULT_CHAT_FRAME:AddMessage("  /mlbc quality 0-6       设置记录/通报的最低品质（0粗糙 2绿色 3蓝色 4紫色 5橙色 6神器）")
        DEFAULT_CHAT_FRAME:AddMessage("  /mlbc keepdays <天数>   设置记录保留天数")
    end

    if p == "" or p == "h" or p == "help" then
        printHelp()
        return
    end

    if p == "show" or p == "s" then
        ToggleFrame()
        return
    end

    if p == "toggle" or p == "t" then
        ToggleMonitorChat()
        return
    end

    -- 新增：/mlbc quality #
    local _, _, q = string.find(p, "^quality (%d)$")
    if q then
        q = tonumber(q)
        if q >= 0 and q <= 6 then
            MasterLootLogDB.qualityThreshold = q
            if MasterLootLogFrame then
                MasterLootLogFrame.title:SetText(string.format("MasterLoot 本周分配记录（只记录 %s%s|r 及以上品质）",
                    ITEM_QUALITY_COLORS[q].hex, Quality[q]))
            end
            DEFAULT_CHAT_FRAME:AddMessage("|cff33ff99[MasterLootByClass]|r 品质阈值已设为 " ..
            q .. ". " .. ITEM_QUALITY_COLORS[q].hex .. Quality[q])
        else
            DEFAULT_CHAT_FRAME:AddMessage("|cff33ff99[MasterLootByClass]|r 品质数字应在 0-6 之间")
        end
        return
    end

    local _, _, d = string.find(p, "^keepdays (%d+)$")
    if d then
        d = tonumber(d)
        MasterLootLogDB.keepDays = d
        DEFAULT_CHAT_FRAME:AddMessage("|cff33ff99[MasterLootByClass]|r 记录保留天数已设为 " .. d .. " 天")
        return
    end

    -- 未知参数
    DEFAULT_CHAT_FRAME:AddMessage("|cff33ff99[MasterLootByClass]|r 未知参数：" .. param)
    printHelp()
end

------------------------------------------------
-- 监控团队/小队聊天：只要出现分配行就记录
------------------------------------------------
local function CatchAssignmentChat(text)
    -- 格式1： [小块的优质毛皮] 分配给  (小队2) 尼麦艾德
    -- 格式2： [小块的优质毛皮] 随机分配给  (小队2) 尼麦艾德
    -- 1. 找物品部分（“分配给”之前）
    local _, _, link = string.find(text, "^(.-) 分配给")
    if not link then
        _, _, link = string.find(text, "^(.-) 随机分配给")
    end

    -- 低品质直接忽略
    if not ItemQualityOK(link) then
        DEFAULT_CHAT_FRAME:AddMessage("品质低于阈值，不符合记录")
        return
    end

    -- 2. 找人名（右括号之后）
    local _, _, name = string.find(text, "%(小队%d+%) (.+)$")

    if not (link and name) then return end

    -- 3. 写入本周日志
    table.insert(MasterLootLogDB.log, {
        itemLink = link,
        player = name,
        time = time(),
        dateStr = date("%m-%d %H:%M")
    })
end

-- 注册事件
local logFrame = CreateFrame("Frame")
logFrame:RegisterEvent("CHAT_MSG_RAID")
logFrame:RegisterEvent("CHAT_MSG_RAID_LEADER")
logFrame:RegisterEvent("CHAT_MSG_PARTY")
logFrame:SetScript("OnEvent", function()
    if MasterLootLogDB.isMonitorChat then
        if (string.find(arg1, "分配给") or string.find(arg1, "随机分配给")) then
            local lootmethod, masterlooterPartyID = GetLootMethod()
            debugPrint("拾取模式:" .. lootmethod .. ", 分配者在小队中编号: " .. tostring(masterlooterPartyID))
            if lootmethod == "master" then
                if (masterlooterPartyID == nil) or (masterlooterPartyID > 0) then
                    CatchAssignmentChat(arg1)
                end
            end
        end
    end
end)


------------------------------------------------
-- 小地图按钮
------------------------------------------------

-- 创建按钮
local mlMiniBtn = CreateFrame("Button", "MLBC_MiniMapBtn", Minimap)
mlMiniBtn:SetWidth(32)
mlMiniBtn:SetHeight(32)
mlMiniBtn:SetFrameStrata("MEDIUM")
mlMiniBtn:SetFrameLevel(8)
mlMiniBtn:SetHighlightTexture("Interface\\Minimap\\UI-Minimap-ZoomButton-Highlight")

-- 图标
local icon = mlMiniBtn:CreateTexture(nil, "BACKGROUND")
icon:SetWidth(20)
icon:SetHeight(20)
icon:SetPoint("CENTER", mlMiniBtn, "CENTER", 0, 1)
icon:SetTexture("Interface\\GroupFrame\\UI-Group-MasterLooter")
mlMiniBtn.icon = icon

-- 边框
local overlay = mlMiniBtn:CreateTexture(nil, "OVERLAY")
overlay:SetWidth(53)
overlay:SetHeight(53)
overlay:SetPoint("TOPLEFT", mlMiniBtn, "TOPLEFT", 0, 0)
overlay:SetTexture("Interface\\Minimap\\MiniMap-TrackingBorder")

-- 拖动功能
mlMiniBtn:SetMovable(true)
mlMiniBtn:EnableMouse(true)
mlMiniBtn:RegisterForDrag("LeftButton")
mlMiniBtn:RegisterForClicks("LeftButtonUp", "RightButtonUp")

local function UpdatePosition()
    local angle = MasterLootLogDB.minimapAngle or 180
    local x = 80 * cos(angle)
    local y = 80 * sin(angle)
    mlMiniBtn:SetPoint("CENTER", Minimap, "CENTER", x, y)
end

mlMiniBtn:SetScript("OnDragStart", function()
    this:LockHighlight()
    this:SetScript("OnUpdate", function()
        local mx, my = Minimap:GetCenter()
        local px, py = GetCursorPosition()
        local scale = Minimap:GetEffectiveScale()
        px, py = px / scale, py / scale

        local angle = math.deg(math.atan2(py - my, px - mx))
        MasterLootLogDB.minimapAngle = angle
        UpdatePosition()
    end)
end)

mlMiniBtn:SetScript("OnDragStop", function()
    this:SetScript("OnUpdate", nil)
    this:UnlockHighlight()
end)

-- 点击事件（移除右键功能）
mlMiniBtn:SetScript("OnClick", function()
    if arg1 == "LeftButton" then
        ToggleFrame()
    elseif arg1 == "RightButton" then
        ToggleMonitorChat()
    end
end)

-- Tooltip（只显示信息，移除右键提示）
mlMiniBtn:SetScript("OnEnter", function()
    GameTooltip:SetOwner(this, "ANCHOR_LEFT")
    GameTooltip:SetText("MasterLootByClass, 命令 /mlbc", 1, 1, 1)
    GameTooltip:AddLine(" ")
    GameTooltip:AddLine("左键  打开/关闭分配记录", 0.2, 1, 0.2)
    GameTooltip:AddLine("右键  切换监控模式", 0.2, 1, 0.2)
    GameTooltip:AddLine("拖动: 移动按钮", 0.2, 1, 0.2)
    GameTooltip:AddLine(" ")
    GameTooltip:AddLine(
        "当前品质记录阈值: " ..
        (MasterLootLogDB.qualityThreshold or 2) ..
        ". " ..
        ITEM_QUALITY_COLORS[MasterLootLogDB.qualityThreshold or 2].hex .. Quality[MasterLootLogDB.qualityThreshold or 2],
        0.8,
        0.8, 0.8)
    GameTooltip:AddLine("使用命令/mlbc quality 0-6 切换阈值", 0.8, 0.8, 0.8)
    GameTooltip:AddLine(" ")
    GameTooltip:AddLine("当前记录保留天数：" .. MasterLootLogDB.keepDays, 0.8, 0.8, 0.8)
    GameTooltip:AddLine("使用命令/mlbc keepdays <天数> 设置记录保留天数", 0.8, 0.8, 0.8)
    GameTooltip:Show()
end)

mlMiniBtn:SetScript("OnLeave", function()
    GameTooltip:Hide()
end)

-- 初始位置
UpdatePosition()
mlMiniBtn:Show()
